package com.xjtu.platform.security.forgetpassword.imply;

import com.xjtu.platform.common.Utils;
import com.xjtu.platform.security.forgetpassword.ForgetPasswordDto;
import com.xjtu.platform.security.forgetpassword.ForgetPasswordService;
import com.xjtu.platform.security.forgetpassword.dao.ForgetPasswordDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class ForgetPasswordImply implements ForgetPasswordService {
    @Resource
    ForgetPasswordDao forgetPasswordDao;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String setRedisCode(String user_id) {
        String code = Utils.produceCode();
        redisTemplate.boundValueOps(user_id).set(code, 600, TimeUnit.SECONDS);
        return code;
    }

    public String getRedisValue(String user_id){
        return redisTemplate.boundValueOps(user_id).get();
    }


    @Override
    public boolean checkUser(ForgetPasswordDto dto) {
        int cont = forgetPasswordDao.checkUser(dto);
        return cont > 0;
    }

    @Override
    public String getEmail(ForgetPasswordDto dto) {

        String email = forgetPasswordDao.getEmail(dto);

        return email;
    }

    @Override
    public void sendEmail(ForgetPasswordDto dto) {
        forgetPasswordDao.sendEmail(dto);
    }

    @Override
    public boolean updatePwd(ForgetPasswordDto dto) {


        if (dto.getCode().equals(getRedisValue(dto.getUser_id()))) {
            forgetPasswordDao.updatePwd(dto);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String findConde(ForgetPasswordDto dto) {

        String code = forgetPasswordDao.findCode(dto);

        if (code.equals(null)) {
            return null;
        } else {

            return code;
        }

    }


}
